<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons')
import resize from './mixins/resize'
import { getToken } from '@/utils/auth'
import { getPredictResult } from '@/api/charts'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null,
      listQuery: {
        token: undefined,
        year: undefined,
        month: undefined,
        day: undefined,
        hour: undefined,
        minute: undefined,
        weekday: undefined
      },
      timer: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
    this.timer = setInterval(() => {
      setTimeout(this.initChart, 0)
    }, 1000 * 60 * 10)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
    clearInterval(this.timer)
    this.timer = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      const datetime = new Date()
      this.listQuery.token = getToken()
      this.listQuery.year = datetime.getFullYear()
      this.listQuery.month = datetime.getMonth() + 1
      this.listQuery.day = datetime.getDate()
      this.listQuery.hour = datetime.getHours()
      this.listQuery.minute = datetime.getMinutes()
      this.listQuery.weekday = datetime.getDay()
      getPredictResult(this.listQuery).then(response => {
        this.chart.setOption({
          title: {
            text: '预计各站客流',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['进站人数', '出站人数'],
            left: 'left'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          toolbox: {
            feature: {
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: response.label
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '进站人数',
              type: 'line',
              stack: '总量',
              data: response.in_list
            },
            {
              name: '出站人数',
              type: 'line',
              stack: '总量',
              data: response.out_list
            }
          ]
        })
      })
    }
  }
}
</script>

